﻿using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using cludg.Domain.Content;
using System.Linq;
using cludg.Web.ViewModels;

namespace cludg.Web.RenderHelpers
{
	public static class TagsHelper
	{
		public static string TagUrl(this HtmlHelper html, string tagName)
		{
			return UrlHelper.GenerateUrl(
					null,
					"Index",
					"Home",
					null,
					html.ViewContext.RequestContext.HttpContext.Request.Url.Host,
					null,
					new RouteValueDictionary { { "tag", tagName } },
					html.RouteCollection,
					html.ViewContext.RequestContext,
					true);
		}

		public static string TagUrl(this HtmlHelper html, Tag tag)
		{
			return TagUrl(html, tag.Name);
		}

		public static MvcHtmlString TagLink(this HtmlHelper html, Tag tag)
		{
			return MvcHtmlString.Create(string.Format("<a href=\"{0}\">{1}</a>",
				TagUrl(html, tag), tag.Name.ToLowerInvariant()));
		}

		public static MvcHtmlString TagLink(this HtmlHelper html, TagCountModel tagCountModel)
		{
			string tagClass = GetTagClass(tagCountModel.TagCount, tagCountModel.TotalPosts);
			return MvcHtmlString.Create(string.Format("<a href=\"{0}\" class=\"{1}\">{2}</a>",
				TagUrl(html, tagCountModel.Tag), tagClass, tagCountModel.Tag.ToLowerInvariant()));
		}

		public static MvcHtmlString TagLinks(this HtmlHelper html, IEnumerable<Tag> tags)
		{
			return MvcHtmlString.Create(string.Join(", ", (from tag in tags select TagLink(html, tag))));
		}

		public static string GetTagClass(long category, long articles)
		{
			var result = (category * 100) / articles;
			if (result <= 1)
				return "tag1";
			if (result <= 4)
				return "tag2";
			if (result <= 8)
				return "tag3";
			if (result <= 12)
				return "tag4";
			if (result <= 18)
				return "tag5";
			if (result <= 30)
				return "tag6";
			return result <= 50 ? "tag7" : "tag8";
		}
	}
}